<?php 
include '../../../wp-blog-header.php';
header('HTTP/1.0 200 OK');
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];


$pods = new Pod('deal');
$pods->page = 1;
$pods->search = false;
//Find all deals having Lat Long data. 
$pods->findRecords("id DESC", -1, "t.camp_end > ".fix_date()." AND Length(t.latlng) > 0 AND t.sale = 1");

$i=0;
while ($pods->fetchRecord())
{
    $deal_name = $pods->get_field('name');
    if(strlen($deal_name) > 85){
    	$deal_name = substr($deal_name,0,85).' ...';
    }
    
    $lat_lng = $pods->get_field('latlng');
    $deal_cat = $pods->get_field('camp_cat.name');
    $deal_link = BUZZR_URL.'/deals/'.$pods->get_field('camp_link');
    $image = $pods->get_field('image');
  	$deal_image =  wp_get_attachment_image_src($image[0][ID], 'thumbnail', false);
  	$deal_image = $deal_image[0];
  	
  	if(empty($deal_image)){
  		$image = $pods->get_field('brand.logo');
  		$deal_image =  wp_get_attachment_image_src($image[0][ID], 'thumbnail', false);
  		$deal_image = $deal_image[0];
  	}
  	
  	$deal_location = $pods->get_field('location');
  	if(empty($deal_location)){
  		$deal_location = $pods->get_field('deal_address');
  	}
  	
    if(empty($deal_location)){
  		$deal_location = $pods->get_field('brand.location');
  	}
	
	if(strlen($deal_location) > 150){
    	$deal_location = substr($deal_location,0,150).' ...';
    }
  	
    $latarr = explode(',',$lat_lng);  //latarr[0] has Latitude AND latarr[1] has Longitude
    $distance = (6371 * acos(cos(deg2rad((double)$center_lat)) * cos(deg2rad((double)$latarr[0])) * cos(deg2rad((double)$latarr[1]) - deg2rad((double)$center_lng)) + sin(deg2rad((double)$center_lat)) * sin(deg2rad((double)$latarr[0])))); //constant 6371 is for distance in km
    
    if(!empty($deal_image)){
	    if(!empty($latarr[0]) && !empty($latarr[1])){
	      if($distance <= $radius){
	         $markers[$i]['lat'] = $latarr[0];
	         $markers[$i]['lng'] = $latarr[1];
	         $markers[$i]['title'] = $deal_name;
	         $markers[$i]['tag'] = $deal_cat;
	         $markers[$i]['sanitized_tag'] = sanitize_title($deal_cat);
	         $markers[$i]['link'] = $deal_link;
	         $markers[$i]['image'] = $deal_image;
	         $markers[$i]['location'] = strip_tags($deal_location);
	         $i++; 
	      }
	    }
    }
}

if(!empty($markers)){
  $markers['markers'] = $markers;
  echo json_encode($markers);
}else{
  $markers['markers'] = 'none';
  echo json_encode($markers);
}
?>